#include "stdio.h"
#include "stdlib.h"
#define SIZE 10
#define PORT 15
#define BUFFERSIZE 512

int main(int argc, char *argv[])
{

   char *pid = argv[0];
   //Do we have fork?
   char sendBuffer[SIZE][BUFFERSIZE];
   char receiveBuffer[BUFFERSIZE];
   int n = 0;
   int connections[SIZE];
   int connection = -1;
   int counter = 0;
   int i, j, k;
   int bytes_read = 0;
   char c;

   while (1)
   {
      //Handle Connections
      connection = accept(PORT);
      if (connection != -1)
      {
         connections[counter] = connection;
         counter++;
         printf("Accepting incoming connection.\n");
      }


      bytes_read = read(0, &c,1);

      if (bytes_read == 1){
         exit(0);
      }


      //Handle read/write
      for (i = 0; i < counter; i++)
      {
         if (connections[i] != -1)
         {
            //Receieve Data
            n = read(connections[i], receiveBuffer, BUFFERSIZE);
            if (n == -1)
            {
               printf("Error on read.");
            }
            else{


               if (strlen(receiveBuffer) > 0 && n> 0){
                  strcat(sendBuffer[i], receiveBuffer);
                  printf("Received: %s FROM: %d READ: %d LEN: %d\n", receiveBuffer, connections[i], n, strlen(receiveBuffer));

                  //Disconnect a client
                  if (strcmp(receiveBuffer, ".\n") == 0){
                     printf("Removing connection to host: %d\n", connections[i]);
                     memset(sendBuffer[i], 0, BUFFERSIZE);
                     connections[i] = -1;
                     for (k = i+1; k < counter; k++){
                        connections[k-1] = connections[k]; 
                     }
                     counter--;
                  }

                  //Send data if there is data to send
                  else if (receiveBuffer[strlen(receiveBuffer)-1] == '\n'){
                     printf("got here\n");
                     for (j = 0; j < counter; j++){
                        if (connections[j] != connections[i]){
                           n = write(connections[j], sendBuffer[i], BUFFERSIZE);
                           if (n == -1)
                           {
                              printf("Error on write. \n");
                              //printf("Error on write. Connection: %d Message: %s\n",connections[j], receiveBuffer );
                           }
                           else{
                              printf("Sent to: %d message: %s written: %d \n" , connections[j], sendBuffer[i], n);
                           }
                        }
                     }
                     memset(sendBuffer[i], 0, BUFFERSIZE);
                  }
               }
            }
         }
      }
   }

   return 0;
}
